<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-description">管理系统用户账户、角色分配和权限设置</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-item">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名、邮箱..."
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-item">
            <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleStatusFilter">
              <el-option label="全部" value="all" />
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="disabled" />
              <el-option label="锁定" value="locked" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="roleFilter" placeholder="角色筛选" @change="handleRoleFilter">
              <el-option label="全部角色" value="all" />
              <el-option label="管理员" value="admin" />
              <el-option label="分析师" value="analyst" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 用户列表 -->
    <div class="users-list">
      <el-card>
        <el-table
          :data="users"
          v-loading="loading"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column label="用户信息" min-width="200">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :size="40" :src="row.avatar">
                  {{ row.username.charAt(0).toUpperCase() }}
                </el-avatar>
                <div class="user-details">
                  <div class="username">{{ row.username }}</div>
                  <div class="email">{{ row.email }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="realName" label="真实姓名" width="120" />
          
          <el-table-column label="角色" width="120">
            <template #default="{ row }">
              <el-tag :type="getRoleType(row.role)" size="small">
                {{ getRoleText(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="lastLogin" label="最后登录" width="180" />
          
          <el-table-column prop="createTime" label="创建时间" width="180" />
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="editUser(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  size="small"
                  :type="row.status === 'active' ? 'warning' : 'success'"
                  @click="handleToggleUserStatus(row)"
                >
                  {{ row.status === 'active' ? '禁用' : '启用' }}
                </el-button>
                <el-dropdown @command="handleCommand" trigger="click">
                  <el-button size="small" type="info">
                    更多
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="`reset-${row.id}`">
                        <el-icon><Key /></el-icon>
                        重置密码
                      </el-dropdown-item>
                      <el-dropdown-item :command="`view-${row.id}`">
                        <el-icon><Document /></el-icon>
                        查看日志
                      </el-dropdown-item>
                      <el-dropdown-item :command="`delete-${row.id}`" divided>
                        <el-icon><Delete /></el-icon>
                        删除用户
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 批量操作 -->
        <div v-if="selectedUsers.length > 0" class="batch-actions">
          <span class="selected-info">已选择 {{ selectedUsers.length }} 个用户</span>
          <el-button-group>
            <el-button @click="batchEnable">批量启用</el-button>
            <el-button @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" @click="batchDelete">批量删除</el-button>
          </el-button-group>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalUsers"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEditing ? '编辑用户' : '新增用户'"
      width="50%"
      class="user-dialog"
    >
      <el-form 
        ref="userFormRef" 
        :model="userForm" 
        :rules="userFormRules" 
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="userForm.username" 
                placeholder="请输入用户名"
                :disabled="isEditing"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="userForm.email" 
                placeholder="请输入邮箱"
                type="email"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input 
                v-model="userForm.realName" 
                placeholder="请输入真实姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="userForm.phone" 
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="选择角色">
                <el-option label="管理员" value="admin" />
                <el-option label="分析师" value="analyst" />
                <el-option label="普通用户" value="user" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" placeholder="选择状态">
                <el-option label="正常" value="active" />
                <el-option label="禁用" value="disabled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="!isEditing" label="密码" prop="password">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input 
            v-model="userForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Edit, ArrowDown, Key,
  Document, Delete
} from '@element-plus/icons-vue'
import { getUserList, createUser, updateUser, deleteUser, toggleUserStatus, resetUserPassword } from '@/api/system'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('all')
const roleFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const totalUsers = ref(0)
const selectedUsers = ref([])

const userDialogVisible = ref(false)
const isEditing = ref(false)
const userFormRef = ref(null)

// 用户列表数据
const users = ref([])

// 用户表单数据
const userForm = ref({
  id: null,
  username: '',
  email: '',
  realName: '',
  phone: '',
  role: '',
  status: 'active',
  password: '',
  remark: ''
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}



// 加载用户列表
const loadUsers = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      status: statusFilter.value,
      role: roleFilter.value
    }

    const response = await getUserList(params)
    if (response.success) {
      users.value = response.data.users
      totalUsers.value = response.data.pagination.total_count
    } else {
      ElMessage.error(response.message || '加载用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

const handleStatusFilter = () => {
  currentPage.value = 1
  loadUsers()
}

const handleRoleFilter = () => {
  currentPage.value = 1
  loadUsers()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadUsers()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadUsers()
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const showCreateDialog = () => {
  isEditing.value = false
  userForm.value = {
    id: null,
    username: '',
    email: '',
    realName: '',
    phone: '',
    role: '',
    status: 'active',
    password: '',
    remark: ''
  }
  userDialogVisible.value = true
}

const editUser = (user) => {
  isEditing.value = true
  userForm.value = { ...user }
  userDialogVisible.value = true
}

const handleSaveUser = async () => {
  try {
    await userFormRef.value.validate()
    saveLoading.value = true

    if (isEditing.value) {
      // 更新用户
      const response = await updateUser(userForm.value.id, userForm.value)
      if (response.code === 200) {
        ElMessage.success(response.message)
        userDialogVisible.value = false
        loadUsers()
      } else {
        ElMessage.error(response.message)
      }
    } else {
      // 新增用户
      const response = await createUser(userForm.value)
      if (response.code === 200) {
        ElMessage.success(response.message)
        userDialogVisible.value = false
        loadUsers()
      } else {
        ElMessage.error(response.message)
      }
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    saveLoading.value = false
  }
}

const handleToggleUserStatus = async (user) => {
  const action = user.status === 'active' ? '禁用' : '启用'

  try {
    await ElMessageBox.confirm(`确定要${action}用户 ${user.username} 吗？`, '确认操作', {
      type: 'warning'
    })

    const response = await toggleUserStatus(user.id)
    if (response.success) {
      ElMessage.success(response.message)
      loadUsers()
    } else {
      ElMessage.error(response.message)
    }
  } catch {
    // 用户取消操作
  }
}

const handleCommand = async (command) => {
  const [action, id] = command.split('-')
  const user = users.value.find(u => u.id === parseInt(id))

  switch (action) {
    case 'reset':
      // 重置密码
      try {
        await ElMessageBox.confirm(`确定要重置用户 ${user.username} 的密码吗？`, '确认重置', {
          type: 'warning'
        })

        const response = await resetUserPassword(id)
        if (response.success) {
          ElMessageBox.alert(
            `密码重置成功！新密码为: ${response.data.new_password}`,
            '重置成功',
            { type: 'success' }
          )
        } else {
          ElMessage.error(response.message)
        }
      } catch {
        // 用户取消
      }
      break

    case 'view':
      // 查看日志
      ElMessage.info('查看用户日志功能开发中...')
      break

    case 'delete':
      // 删除用户
      try {
        await ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？此操作不可恢复！`, '确认删除', {
          type: 'error'
        })

        const response = await deleteUser(id)
        if (response.code === 200) {
          ElMessage.success(response.message)
          loadUsers()
        } else {
          ElMessage.error(response.message)
        }
      } catch {
        // 用户取消
      }
      break
  }
}

const batchEnable = async () => {
  try {
    await ElMessageBox.confirm(`确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`, '批量启用', {
      type: 'warning'
    })
    
    selectedUsers.value.forEach(user => {
      user.status = 'active'
    })
    
    ElMessage.success('批量启用成功')
    selectedUsers.value = []
  } catch {
    // 用户取消
  }
}

const batchDisable = async () => {
  try {
    await ElMessageBox.confirm(`确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`, '批量禁用', {
      type: 'warning'
    })
    
    selectedUsers.value.forEach(user => {
      user.status = 'disabled'
    })
    
    ElMessage.success('批量禁用成功')
    selectedUsers.value = []
  } catch {
    // 用户取消
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复！`, '批量删除', {
      type: 'error'
    })
    
    const selectedIds = selectedUsers.value.map(user => user.id)
    users.value = users.value.filter(user => !selectedIds.includes(user.id))
    
    ElMessage.success('批量删除成功')
    selectedUsers.value = []
  } catch {
    // 用户取消
  }
}

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    analyst: 'warning',
    user: 'info'
  }
  return types[role] || 'info'
}

const getRoleText = (role) => {
  const texts = {
    admin: '管理员',
    analyst: '分析师',
    user: '普通用户'
  }
  return texts[role] || '未知'
}

const getStatusType = (status) => {
  const types = {
    active: 'success',
    disabled: 'danger',
    locked: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    active: '正常',
    disabled: '禁用',
    locked: '锁定'
  }
  return texts[status] || '未知'
}

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header-content p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-card {
  border-radius: 8px;
}

.filter-content {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  min-width: 200px;
}

.users-list {
  background: white;
  border-radius: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.email {
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid #e6e8eb;
  margin-top: 16px;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.user-dialog :deep(.el-dialog__body) {
  padding: 20px;
}
</style>
